﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MvcEngine.Mvc.StarterSite.Controllers;
using MvcEngine.Mvc.Models.ViewModels;
using System.Web.Mvc;
using MvcEngine.Core;
using MvcEngine.Core.Common.Slugs;
using MvcEngine.Core.Repositories;
using System.Web;
using System.Web.Routing;
using MvcEngine.Core.Validation;
using System.Web.Mvc.Html;
using MvcEngine.Mvc.Filters;
using MvcEngine.Contact.Models;
using MvcEngine.Core.Content;
using MvcEngine.Core.Helpers;
using MvcEngine.Mvc.Extensions;
using MvcEngine.Core.Services;
using MvcEngine.Mvc.Controllers;
using MvcEngine.Contact.Components.Extensions;

namespace MvcEngine.Contact.BackOffice.Controllers
{
    public class ContactController : BaseController
    {
        [AcceptVerbs(HttpVerbs.Get)]
        public MvcEngineModel Settings(int ctrId)
        {
            var pageContent = ContentManager.Current.GetPageContent(ctrId);
            Guard.ThrowIfNull(pageContent, string.Format("Page content {0} does not exist.", ctrId));

            ContactSettings settings = new ContactSettings(pageContent);
            ContactSettingsViewModel model = new ContactSettingsViewModel(ctrId, settings);

            return new MvcEngineModelItem<ContactSettingsViewModel>()
            {
                Item = model,
                ViewName = "Settings"
            };
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [AntiForgeryValidationFilter]
        public object Settings(int ctrId, ContactSettings settings)
        {
            if (ModelState.IsValid)
            {
                var pageContent = ContentManager.Current.GetPageContent(ctrId);
                Guard.ThrowIfNull(pageContent, string.Format("Page content {0} does not exist.", ctrId));

                settings.Fields.CopyTo(pageContent.Fields);
                ContentManager.Current.SavePageContent(pageContent);
                return Json(new { model = "valid" });
            }
            return Json(new { model = "invalid", errors = ModelState.GetErrors() });

        }
    }
}
